package com.itheima.proxy.jdk_proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Author 王加鑫
 * @Date 2021/08/06 19:11
 * @Since JDK 1.8
 */
public class JdkProxy implements InvocationHandler{

    private HouseMan houseMan;

    //构造器注入思维
    public JdkProxy(HouseMan houseMan) {
        this.houseMan = houseMan;
    }

    // 对原始方法执行进行拦截并增强
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object ret = null;
        if(method.getName().equals("chuZu")){
            System.out.println("中介帮房东出租房子");
            try {
                ret = method.invoke(houseMan, args);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            System.out.println("中介收取中介费");
        }
        return ret;
    }

    //创造代理对象
    public Object createJdkProxy(){
        return Proxy.newProxyInstance(houseMan.getClass().getClassLoader(), houseMan.getClass().getInterfaces(), this);
    }
}
